<?php
	
	define( 'JOIN', 'SELECT image.stitchid AS stitchid, image.title AS title, image.author AS author, image.creation AS creation, o.tag AS tag FROM image LEFT OUTER JOIN tags AS o ON image.stitchid = o.stitchid' );
	
	class img_info {
		public $stitchid;
		public $author;
		public $creation;
		public $title;
	}
	
	function getFilterString($terms){
		if($terms == '') return '';
		
		$raw_terms = explode(' ', $terms);
		$terms = array();
		
		foreach($raw_terms as $s)
			array_push( $terms, '(tag LIKE "%' . $s . '%" OR title LIKE "%' . $s . '%")' );
		
		return implode(' AND ', $terms);
	}
	
	function getImagesNear($stitchid, $count, $terms) {
		
		$f = stripcslashes($terms == '' ? '' : 'AND ('.getFilterString($terms).')');
		
		$back = $count / 2;
		$b = $stitchid > $back ? $stitchid - $back : 0;
		
		$result = queryImages(JOIN." WHERE image.stitchid >= $b AND stitched > 0 $f GROUP BY image.stitchid ORDER BY image.stitchid LIMIT 0,$count");

		$images;
		for($i=0; $i<count($result); $i++) {
				if(is_null($result[$i])) return $images;
				$images[$i] = convertToImg($result[$i]);
		}

		return $images;
	}
  
	function getNextImage($stitchid, $greater, $terms) {
		
		$f = stripcslashes($terms == '' ? '' : 'AND ('.getFilterString($terms).')');
		if($greater == "true")
			$result = queryImages(JOIN." WHERE image.stitchid > '$stitchid' AND stitched > 0 $f GROUP BY image.stitchid ORDER BY image.stitchid ASC LIMIT 0,1");
		else
			$result = queryImages(JOIN." WHERE image.stitchid < '$stitchid' AND stitched > 0 $f GROUP BY image.stitchid ORDER BY image.stitchid DESC LIMIT 0,1");

		if(is_null($result)) return null;

		return convertToImg($result[0]);
	}

	function getImageInfo($stitchid) {
		$result = queryImages("SELECT * FROM image WHERE stitchid='$stitchid' AND stitched > 0");

		if(is_null($result)) return null;

		return convertToImg($result[0]);
	}

	function convertToImg($result) {
		$img = new img_info;
			$img->stitchid = $result['stitchid'];
			$img->author = $result['author'];
			$img->creation = $result['creation'];
			$img->title = $result['title'];
		return $img;
	}

	function queryImages($query) {

		require 'db_init.php';
		
		$data = mysql_query($query) or die(mysql_error());

		$result;
		$i = 0;
		
		while($row = mysql_fetch_array( $data )) {
			$result[$i] = $row;
			$i++;
		}

		mysql_close();

		return $result;
	}

?>